package com.party.web.web.controller.sign;

import com.google.common.base.Strings;
import com.party.api.dto.wechat.requst.XcxQrCodeRequest;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.StringUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.member.Member;
import com.party.core.model.sign.SignProject;
import com.party.core.model.sign.SignProjectAuthor;
import com.party.core.model.wechatPlatform.WechatOpenMember;
import com.party.core.service.sign.ISignProjectService;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import com.party.web.biz.file.FileBizService;
import com.party.web.biz.sign.SignProjectBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.web.annotation.ControlParam;
import com.party.web.web.annotation.DataControl;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.common.CommonInput;
import com.party.web.web.dto.input.sign.SignProjectInput;
import com.party.web.web.dto.output.sign.SignProjectOutput;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * 签到项目控制器
 * Created by wei.li
 *
 * @date 2017/6/6 0006
 * @time 10:11
 */

@Controller
@RequestMapping(value = "sign/project")
public class SignProjectController {

    @Autowired
    private ISignProjectService signProjectService;

    @Autowired
    private SignProjectBizService signProjectBizService;

    @Autowired
    private FileBizService fileBizService;

    @Autowired
    private IWechatOpenMemberService wechatOpenMemberService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 签到信息列表
     * @param signProjectAuthor 签到信息
     * @param page 分页参数
     * @return 列表信息
     */
    @RequestMapping(value = "list")
    public ModelAndView list(SignProjectAuthor signProjectAuthor, Page page, CommonInput commonInput) {
        ModelAndView modelAndView = new ModelAndView("sign/signProjectList");
        Map<String, Object> params = CommonInput.appendParams(commonInput);

        List<SignProjectOutput> list = signProjectBizService.list(signProjectAuthor, page, params);
        modelAndView.addObject("list", list);
        modelAndView.addObject("page", page);
        modelAndView.addObject("project", signProjectAuthor);
        modelAndView.addObject("input", commonInput);
        return modelAndView;
    }

    /**
     * 签到信息试图
     * @param id 编号
     * @return 交互信息
     */
    @DataControl
    @RequestMapping(value = "view")
    public ModelAndView view(@ControlParam(table = "sign_project", column = "create_by", isRequired = false)String id){
        ModelAndView modelAndView = new ModelAndView("sign/signProjectView");
        SignProject signProject;
        if (Strings.isNullOrEmpty(id)){
            signProject = new SignProject();
            signProject.setApplyCheck(YesNoStatus.YES.getCode());
            signProject.setRankShow(YesNoStatus.YES.getCode());
        }
        else {
            signProject = signProjectService.get(id);
            if (StringUtils.isNotEmpty(signProject.getRule())) {
                String content = StringUtils.unescapeHtml4Video2Iframe(signProject.getRule());
                signProject.setRule(content);
            }
        }
        modelAndView.addObject("signProject", signProject);
        return modelAndView;
    }


    /**
     * 保存签到信息
     * @param signProjectInput 签到项目
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "save")
    public AjaxResult save(SignProjectInput signProjectInput) {
        try {
            AjaxResult ajaxResult = new AjaxResult();
            SignProject signProject = SignProjectInput.transform(signProjectInput);
            String memberId = RealmUtils.getCurrentUser().getId();
            if (StringUtils.isNotEmpty(signProject.getRule())) {
                String content = StringUtils.escapeHtml4Iframe2Video(signProject.getRule().trim());
                signProject.setRule(content);
            }
            if (Strings.isNullOrEmpty(signProjectInput.getId())) {
                signProject.setCreateBy(memberId);
                signProject.setUpdateBy(memberId);
                signProjectService.insert(signProject);
            } else {
                SignProject db = signProjectService.get(signProjectInput.getId());

                signProject.setUpdateBy(memberId);
                signProjectService.update(signProject);

                memberId = db.getCreateBy();
            }
            ajaxResult.setSuccess(true);

            try {
                WechatOpenMember openMember = wechatOpenMemberService.findByType(Constant.WECHAT_ACCOUNT_TYPE_SYSTEM_XCX_SIGN);
                XcxQrCodeRequest qrCodeRequest = new XcxQrCodeRequest();
                qrCodeRequest.setPage("pages/pro/index");
                qrCodeRequest.setScene(signProject.getId());
                String filePath = fileBizService.getUploadCIPath(memberId, "signProject");
                fileBizService.uploadCloudOut(signProject.getId(), filePath, qrCodeRequest, openMember.getAuthorizerAccessToken(), 1);
            } catch (Exception e) {
                logger.error("生成打卡二维码异常", e);
            }
            return ajaxResult;
        } catch (Exception e) {
            logger.error("保存运动打卡项目异常", e);
            return AjaxResult.error("保存项目异常");
        }
    }

    /**
     * 删除签到项目
     *
     * @param id 编号
     * @return 交互数据
     */
    @DataControl
    @ResponseBody
    @RequestMapping(value = "delete")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult delete(@ControlParam(table = "sign_project", column = "create_by") String id) {
        boolean result = signProjectBizService.deleteProjectBiz(id);
        if (result) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("删除失败");
        }
    }
}
